/**
  * @description: g2--多个仪表盘--4
  * @author: hj
  * @update: hj(2020-04-22)
  */

 import React, {Component} from 'react';
 import G2 from '@antv/g2';
 import DataSet from '@antv/data-set';
 import {getMediaById} from '@/service/Api/Chart';
 import { observer,inject,Provider } from 'mobx-react';
 
  
 @inject('chartStore') 
 @observer
 
 
 class MultipleGauge extends Component {
     constructor(props) {
         super(props);
         this.state = {
             params: [],
             data: [],
             forceFit: true, //forceFit自动试用宽度，默认false
             width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
             height: this.props.data.height ? this.props.data.height - 50 : '100%',
             condition: this.props.data.condition ? this.props.data.condition : '',
             pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
             nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
             color: [],
             fields: [],
             xAxis: "",
             title: '',
             chartId: this.props.data.chartId,
             id: this.props.data.componentId,
             chartData: [],
             axisArr: {},
             haveData: false,
             legend: 'top',
 
             dataNull: false, // 暂无数据
 
             // 全局变量
             mainData: [], // 操作组件可操作数据
             mainName: '', // 操作组件可操作当前维度
             mainFlag: false, // 是否是操作组件
 
             pageInitFlag: true,
             affectName: '',
             requireCondition: '',
         };
     };
 
 
     componentWillMount() { //初始化
         const _this = this;
         
         // 预览界面
         if (_this.state.pageFlag == 'preview') {
             // 判断当前组件是否是可操作组件
             const { globalData } = _this.props.chartStore;
             if (globalData.slice().length > 0) {
                 globalData.slice().map((item,index) => {
                     if (item.affect == _this.state.chartId) { // 可操作组件
                         let affectName = item.affectDimension;
                         _this.setState({
                             mainFlag: true,
                             mainName: affectName
                         })
                     }
                 })
             }
 
             _this.interfaceRequest(_this.state.chartId,_this.state.condition);
         } else { // 配置面板
             if (_this.state.nofirst == 'nofirst') {
                 _this.saveHandleData();
             } else {
                 _this.interfaceRequest(_this.state.chartId,_this.state.condition);
             }
         }
     }
 
     // 钩子函数--组件挂载完成后
     componentDidMount() { //初始化
         this.setState({
             haveData: true
         })
     }
     // 接收父组件的数据改变
     componentWillReceiveProps = (nextProps) => {
         const _this = this;
         const { globalData, affectId } = _this.props.chartStore;
 
         // 预览界面---判断是否是变化组件
         if (nextProps.data.pageFlag == 'preview') {
             if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                 globalData.slice().map((item,index) => {
                     if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                         _this.setState({
                             pageInitFlag: false
                         })
                         let condition = {};
                         Object.keys(_this.state.requireCondition).forEach(function(keys){
                             condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                         })
                         _this.interfaceRequest(nextProps.data.chartId,condition);
                     }
                 })
             }
         }
     }
 
     // 数据接口请求
     interfaceRequest = (chartId,condition) => {
         this.setState({
             requireCondition: condition,
         });
 
         let data = {
             charId: chartId,
             condition: condition
         };
         this.getMediaById(data);
     }
 
     // 数据存储刷新
     saveHandleData = () => {
         const { chartArrData } = this.props.chartStore;
         if (chartArrData.slice().length > 0) {
             chartArrData.slice().map((item) => {
                 if (item.id == this.state.chartId) {
                     this.setState({
                         haveData: false
                     },function() {
                         // 数据处理
                         this.handleData(item.data);
                     })
                 }
             })
         }
     }
 
 
     async getMediaById(data) {
         const res = await getMediaById(data);
         if (res.data && res.data.code === 0) {
             let str = res.data;
             if (str.data && str.data.data && str.data.data.length > 0) {
                 // 存储图例原始数据
                 const { saveChartData } = this.props.chartStore;
                 let oldData = {
                     id: this.state.chartId,
                     data: str.data.data
                 }
                 saveChartData(oldData);
 
                 // 数据处理
                 this.handleData(str.data.data);
             } else {
                 this.setState({
                     dataNull: true
                 })
             }
         } else {
             this.setState({
                 dataNull: true
             })
         }
     }
     // 数据处理
     handleData = (storeAllData) => {
         let storeData = storeAllData[0];
         this.setState({
             dataNull: true
         })
 
         // 非预览界面
         if (this.state.pageFlag != 'preview') {
             // 存储可操作组件数据
             if (storeData.affect && storeData.affect.length > 0) {
                 let obj = {
                     id: this.state.chartId,
                     label: storeData.title,
                     dimensionData: []
                 }
                 const { saveAffectData } = this.props.chartStore;
 
                 let dimensionData = [];
                 storeData.affect.slice().map((item,index) => {
                     dimensionData.push(item);
                 })
                 obj.dimensionData = dimensionData;
                 saveAffectData(obj);
             }
             // 存储联动组件数据
             if (storeData.requires && storeData.requires.length > 0) {
                 let obj = {
                     id: this.state.chartId,
                     label: storeData.title,
                     dimensionData: []
                 }
                 const { saveRequireData } = this.props.chartStore;
 
                 let dimensionData = [];
                 storeData.requires.slice().map((item,index) => {
                     dimensionData.push(item);
                 })
                 obj.dimensionData = dimensionData;
                 saveRequireData(obj);
             }
         }
 
         // 页面初始化
         if (this.state.pageInitFlag) {
             if (storeData.affect &&  storeData.affect.length > 0) {
                 this.setState({
                     affectName: storeData.affect[0]
                 });
             }
             // 获取选择项
             if (storeData.conditionValues) {
                 let selectData = storeData.conditionValues[storeData.affect[0]] ? storeData.conditionValues[storeData.affect[0]] : [];
                 this.setState({
                     mainData: selectData
                 });
             }
         }
 
         let oldData = [];
         if (storeData.data.length > 0) {
             this.setState({
                 dataNull: false
             })
             storeData.data.map((item,index) => {
                 let obj = item;
                 oldData.push(obj);
             })
         }
 
         this.setState({
             title: storeData.title,
             chartData: oldData,
             xAxis: "name",
             fields: "",
             axisArr: [],
             color: storeData.colors.split(","),
             haveData: true,
         })
     }
 
     // 渲染多个仪表盘
     renderGauge = (data,index) => {
         // 极坐标下的柱状图
         // 构造数据
         let data1 = [];
         for (let i = 0; i < 100; i++) {
             if (i % 2 == 0) {
                 let item = {};
                 item.type = i + '';
                 item.value = 10;
                 if (i === 50) {
                     item.value = 15;
                 }
                 data1.push(item);
             }
         }
         // console.log('data1',data1);
         
 
         let data2 = [];
         for (let _i = 0; _i < 100; _i++) {
             if (_i % 2 == 0) {
                 let _item = {};
                 _item.type = _i + '';
                 _item.value = 10;
                 if (_i === 50) {
                     _item.value = 15;
                 }
                 if (_i > data.data) {
                     _item.value = 0;
                 }
                 data2.push(_item);
             }
         }
         // console.log('data2',data2);
 
         let chart = new G2.Chart({
             container: 'gauge_'+index,
             forceFit: true,
             height: document.getElementById('gauge_'+index).offsetHeight,
             padding: 0
         });
         chart.scale({
             type: {
                 range: [0, 1]
             },
             value: {
                 sync: true
             }
         });
         chart.legend(false);
         chart.tooltip(false);
         let view1 = chart.view();
         view1.source(data1);
         view1.axis(false);
         view1.coord('polar', {
             startAngle: -9 / 8 * Math.PI,
             endAngle: 1 / 8 * Math.PI,
             innerRadius: 0.68,
             radius: 0.73
         });
         view1.interval().position('type*value').color('#fff').size(2);
 
         let view2 = chart.view();
         view2.source(data1, {
             type: {
                 tickCount: 3
             }
         });
         view2.axis('value', false);
         view2.axis('type', {
             grid: null,
             line: null,
             tickLine: null,
             label: {
                 offset: -7,
                 offsetY: 7,
                 textStyle: {
                     textAlign: 'center',
                     fill: '#fff',
                     fontSize: 12
                 },
                 formatter: function formatter(val) {
                     if (val === '99' || val === '98') {
                     return 100;
                     }
 
                     return val;
                 }
             }
         });
         view2.coord('polar', {
             startAngle: -9 / 8 * Math.PI,
             endAngle: 1 / 8 * Math.PI,
             innerRadius: 0.85,
             radius: 0.48
         });
         view2.interval().position('type*value').color('#fff').size(2);
 
         let view3 = chart.view();
         view3.source(data2);
         view3.axis(false);
         view3.coord('polar', {
             startAngle: -9 / 8 * Math.PI,
             endAngle: 1 / 8 * Math.PI,
             innerRadius: 0.68,
             radius: 0.73
         });
         let color = this.state.color[index] ? this.state.color[index] : this.state.color[0];
         view3.interval().position('type*value').color('value', parseInt(data.tier) == 1 ? '#c00000' : parseInt(data.tier) == 2 ? '#ff0000' : parseInt(data.tier) == 3 ? '#ffa500' : parseInt(data.tier) == 4 ? '#ffff00' : parseInt(data.tier) == 5 ? '#52C72E' : '#0FA33D').opacity(1).size(2);
         view3.guide().text({
             position: ['50%', '65%'],
             content: data.data+'%',
             style: {
             fill: parseInt(data.tier) == 1 ? '#c00000' : parseInt(data.tier) == 2 ? '#ff0000' : parseInt(data.tier) == 3 ? '#ffa500' : parseInt(data.tier) == 4 ? '#ffff00' : parseInt(data.tier) == 5 ? '#52C72E' : '#0FA33D',
             fontSize: 16,
             fontFamily: 'myNumberFamily',
             textAlign: 'center',
             textBaseline: 'middle'
             }
         });
 
         chart.render();
     }
 
     // 改变全局变量
     onGlobalVariable = (val) => {
         const { saveAffectId } = this.props.chartStore;
         saveAffectId(this.state.chartId);
         this.props.onGlobalVariable(val);
     }
     
     
 
     render() {
         const _this = this;
         let Layer = this.props.layer;
         let selectVal = this.state.requireCondition[this.state.affectName] ? this.state.requireCondition[this.state.affectName] : '';
 
         let chartData = this.state.chartData;
         let haveData = this.state.haveData;
         if (haveData && chartData.length > 0) {
             _this.setState({
                 haveData: false
             });
 
             setTimeout(()=> {
                 chartData.map((item,index) => {
                     document.getElementById('gauge_'+index).innerHTML = '';
                     _this.renderGauge(item,index);
                 })
             },100)
 
         }
 
         return (
             <div id={this.state.id + '_' + this.state.chartId}  style={{zIndex: 9999,width: this.state.width, height: this.state.height,padding: '40px 2% 10px 2%'}}>
                 <Layer width={this.state.width} 
                         title={this.state.title} 
                         chartId={this.state.chartId} 
                         choiceData={this.state.mainData} 
                         selectVal={selectVal}
                         onGlobalVariable={this.onGlobalVariable}
                 ></Layer>
                 <div id={'chart_' + this.state.id + '_' + this.state.chartId} style={{height: this.state.height,overflow: 'hidden'}}>
                     {chartData.length > 0 ? chartData.map((item,index) => {
                         return (
                             <div style={{width:( chartData.length > 4 && index > 1) ? '33.3%' : '50%',height: this.state.height / 2,display: 'inline-block'}}>
                                 <div id={'gauge_'+index} style={{width: '100%',height: 'calc(100% - 50px)'}}></div>
                                 <p style={{width: '100%',height: '24px',lineHeight: '24px',fontSize: '14px',color: '#8AE5EB',margin: 0,textAlign: 'center',overflow: 'hidden'}}>{item.title ? item.title : ''}</p>
                                 <p style={{width: '100%',height: '24px',lineHeight: '24px',fontSize: '12px',color: '#24C6F5',margin: 0,textAlign: 'center'}}>{item.botmText ? item.botmText : ''}</p>
                             </div>
                         )
                     }) : 
                     this.state.dataNull && <p style={{height: this.state.height,lineHeight: this.state.height+'px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>
                     }
                 </div>
             </div>
         )
     }
 
 
 }
 
 export default MultipleGauge;
 
 